package com.ncloud.monitor.wrapper.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.ncloud.monitor.zabbix4j.ZabbixApi;
import com.ncloud.monitor.zabbix4j.ZabbixApiException;
import com.ncloud.monitor.zabbix4j.ZabbixApiParamter;
import com.ncloud.monitor.zabbix4j.host.HostGetRequest;
import com.ncloud.monitor.zabbix4j.host.HostGetResponse;
import com.ncloud.monitor.zabbix4j.hostinteface.HostInterfaceGetRequest;
import com.ncloud.monitor.zabbix4j.hostinteface.HostInterfaceGetResponse;
import com.ncloud.monitor.zabbix4j.item.ItemGetRequest;
import com.ncloud.monitor.zabbix4j.item.ItemGetResponse;
import com.ncloud.monitor.zabbix4j.item.ItemGetResponse.Result;
import com.xiaoleilu.hutool.util.NumberUtil;

@Service
public class ZabbixMonitor{
	
	/**
	 * 1. 获取hostId
	 * 2. 获取CPU、memory，disk使用情况
	 * 3. 组合返回数据
	 * @param hostName
	 * @return
	 * @throws Exception 
	 */
	public List<Map<String, Object>> getUsedRatioByHostName(String hostName) throws Exception {
        try {
			Integer hostId = getHostIdByHostName(hostName);
			List<Result> items = null;
			if(hostId!=null) items = getItemsByHostId(hostId);
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			list = origResult(items);
			return list;
		} finally {
		}
	}
	
	public List<Map<String, Object>> getUsedRatioByHostManageIp(String manageIp) {
		try {
			Integer hostId = getHostIdByInterfaceIp(manageIp);
			List<Result> items = null;
			if(hostId!=null) items = getItemsByHostId(hostId);
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			list = origResult(items);
			return list;
		} finally {
		}
	}

	private Integer getHostIdByInterfaceIp(String manageIp) {
		try {
			HostInterfaceGetRequest request = new HostInterfaceGetRequest();
			HostInterfaceGetRequest.Params params = request.getParams();
	        params.getFilter().addIp(manageIp);
	        HostInterfaceGetResponse response = ZabbixApi.getZabbixApi().hostInterface().get(request);
			if(!response.getResult().isEmpty()){
				HostInterfaceGetResponse.Result result = response.getResult().get(0);
				return result.getHostid();
			}
		} catch (ZabbixApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return null;
	}

	private List<Map<String, Object>> origResult(List<Result> items) {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		String cpuIdel = "0";
		String memoryFree = "0";
		String memoryTotal = "0";
		String diskFree = "0";
		String diskTotal = "0";
        if(items !=null){
			for (Result item : items) {
				if(ZabbixApiParamter.KEY_.CPU_IDEL.value.equals(item.getKey_())){
					cpuIdel = item.getLastvalue();
				}else if (ZabbixApiParamter.KEY_.MEMORY_FREE.value.equals(item.getKey_())) {
					memoryFree = item.getLastvalue();
				}else if (ZabbixApiParamter.KEY_.MEMORY_TOTAL.value.equals(item.getKey_())) {
					memoryTotal = item.getLastvalue();
				}else if (ZabbixApiParamter.KEY_.DISK_FREE.value.equals(item.getKey_())) {
					diskFree = item.getLastvalue();
				}else if (ZabbixApiParamter.KEY_.DISK_TOTAL.value.equals(item.getKey_())) {
					diskTotal = item.getLastvalue();
				}
				
			}
        }
        Map<String, Object> map = new HashMap<String, Object>();
        double cpuidel = NumberUtil.round(cpuIdel, 2);
		map.put("cpuIdel", cpuidel);
		double cpuUsed = NumberUtil.round(100 - cpuidel,2);
		map.put("cpuUsed", cpuUsed);
		map.put("cpuTotal", 100.00);
    
        BigDecimal mfree = NumberUtil.div(memoryFree, (1024*1024*1024)+"",2);
		map.put("memoryFree", mfree);
		BigDecimal total = NumberUtil.div(memoryTotal, (1024*1024*1024)+"",2);
		map.put("memoryUsed", NumberUtil.sub(total, mfree));
		map.put("memoryTotal", total);
    
        BigDecimal dfree = NumberUtil.div(diskFree, (1024*1024*1024)+"",2);
		map.put("diskFree", dfree);
		BigDecimal dtotal = NumberUtil.div(diskTotal, (1024*1024*1024)+"",2);
		map.put("diskUsed", NumberUtil.sub(dtotal, dfree));
		map.put("diskTotal", total);
        
        if(!map.isEmpty()) list.add(map);
        return list;
	}

	private List<Result> getItemsByHostId(Integer hostId) {
		try {
			String key_ = "system";
			ItemGetRequest request = new ItemGetRequest();
			ItemGetRequest.Params params = request.getParams();
			List<Integer> hostIds = new ArrayList<Integer>();
			hostIds.add(hostId);
			params.setHostids(hostIds);
			params.getSearch().setKey_(key_);
			params.getFilter().addKey_(ZabbixApiParamter.KEY_.CPU_IDEL.value)
				.addKey_(ZabbixApiParamter.KEY_.MEMORY_FREE.value).addKey_(ZabbixApiParamter.KEY_.MEMORY_TOTAL.value)
				.addKey_(ZabbixApiParamter.KEY_.DISK_FREE.value).addKey_(ZabbixApiParamter.KEY_.DISK_TOTAL.value);
			ItemGetResponse response = ZabbixApi.getZabbixApi().item().get(request);
			
			List<Result> result = response.getResult();
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	private Integer getHostIdByHostName(String hostName) {
		try {
			HostGetRequest request = new HostGetRequest();
	        HostGetRequest.Params params = request.getParams();
	        HostGetRequest.Params.Filter filter = params.getFilter();
	        List<String> host = new ArrayList<String>();
	        host.add(hostName);
			filter.setHost(host);
			HostGetResponse response = ZabbixApi.getZabbixApi().host().get(request);
			
			HostGetResponse.Result result = response.getResult().get(0);
			return result.getHostid();
		} catch (ZabbixApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
